import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_base_library/app/themes/app_colors.dart';

int maxCountdown = 60;

// ignore: must_be_immutable
class CountDownButton extends StatefulWidget {
  final String prefixTitle;
  final GestureTapCallback? onTap;
  bool startCountDown = false;
  CountDownButton({
    Key? key,
    required this.prefixTitle,
    this.startCountDown = false,
    this.onTap,
  }) : super(key: key);
  @override
  State<CountDownButton> createState() => _CountDownButtonState();
}

class _CountDownButtonState extends State<CountDownButton> {
  int second = maxCountdown;
  bool isCountingDown = false;
  Timer? timer;
  @override
  void initState() {
    super.initState();
    isCountingDown = false;
    second = maxCountdown;
  }

  @override
  void dispose() {
    super.dispose();
    if (timer != null) {
      timer!.cancel();
    }
  }

  void startCountdown() {
    if (isCountingDown) {
      return;
    }
    isCountingDown = true;
    var duration = const Duration(seconds: 1);
    timer = Timer.periodic(duration, (timer) {
      setState(() {
        second--;
        if (second == 0) {
          second = maxCountdown;
          timer.cancel();
          isCountingDown = false;
          widget.startCountDown = false;
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.startCountDown) {
      startCountdown();
    }
    return GestureDetector(
      onTap: () {
        if (!isCountingDown) {
          widget.onTap!();
        }
      },
      child: Container(
        width: 120,
        height: 50,
        alignment: Alignment.center,
        child: Text(
          isCountingDown
              ? "${widget.prefixTitle}($second)s"
              : widget.prefixTitle,
          style: TextStyle(
            color:
                isCountingDown ? AppColors.lightGray : AppColors.kPrimaryColor,
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}
